package com.nrgedge.magnolia.form.processors;

import info.magnolia.cms.core.Content;
import info.magnolia.context.MgnlContext;
import info.magnolia.module.ModuleRegistry;
import info.magnolia.module.form.processors.AbstractFormProcessor;
import info.magnolia.module.form.processors.FormProcessorFailedException;

import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import net.tanesha.recaptcha.ProxyReCaptchaImpl;
import net.tanesha.recaptcha.ReCaptchaResponse;

import com.nrgedge.magnolia.ReCaptchaModule;

public class ReCaptchaFormProcessor extends AbstractFormProcessor {
		
	@Override
	protected void internalProcess(Content content,	Map<String, Object> parameters) throws FormProcessorFailedException {
		final HttpServletRequest request = MgnlContext.getWebContext().getRequest();
		final ReCaptchaModule module = (ReCaptchaModule) ModuleRegistry.Factory.getInstance().getModuleInstance("recaptcha");
		
		final String remoteAddr = request.getRemoteAddr();    
        
        final String proxyHost = module.getProxyHost();
        final String proxyPort = module.getProxyPort();
        final String proxyUsername = module.getProxyUsername();
    	final String proxyPassword = module.getProxyPassword();
    	
    	final ProxyReCaptchaImpl reCaptcha = new ProxyReCaptchaImpl(proxyHost, proxyPort != null ? Integer.parseInt(proxyPort) : 0, proxyUsername, proxyPassword);
        
        reCaptcha.setPrivateKey(module.getPrivateKey());

        final String challenge = request.getParameter("recaptcha_challenge_field");
        final String uresponse = request.getParameter("recaptcha_response_field");
        final ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(remoteAddr, challenge, uresponse);
        
        if (!reCaptchaResponse.isValid()) {
        	throw new FormProcessorFailedException("ReCaptchaFormProcessor.errorMessage");
        }
	}

}
